package com.sn.system.common.validator.validators;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sn.system.common.utils.CheckUtils;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public abstract class AbstractRegexValidator extends FieldValidatorSupport {

	    public void validate(Object object) throws ValidationException {
	    	doValidate(object);
	    }
	    
	    protected void doValidate(Object object) throws ValidationException {
	        String fieldName = getFieldName();
	        Object value = this.getFieldValue(fieldName, object);
	        // if there is no value - don't do comparison
	        // if a value is required, a required validator should be added to the field
	        if (value == null || getExpression() == null) {
	            return;
	        }
	        
	        // XW-375 - must be a string
	        if (!(value instanceof String)) {
	            return;
	        }

	        // string must not be empty
	        String str = ((String) value).trim();
	        if (str.length() == 0) {
	            return;
	        }

	        // match against expression
	        Pattern pattern;
	        pattern = Pattern.compile(getExpression(), Pattern.CASE_INSENSITIVE);        
//	        if (isCaseSensitive()) {
//	            pattern = Pattern.compile(getExpression());
//	        } else {
//	            pattern = Pattern.compile(getExpression(), Pattern.CASE_INSENSITIVE);
//	        }

	        String compare = (String) value;
	        
	        Matcher matcher = pattern.matcher( compare );

	        if (!matcher.matches()) {
	            addFieldError(fieldName, object);
	            return;
	        }
	        if(CheckUtils.isNumber(getMaxLength())){
	        	 if(str.length()>Integer.parseInt(getMaxLength())){
	             	addFieldError(getFieldName(), object);
	             }
	        }
	    }

	    protected abstract String getExpression();
	    
	    protected abstract String getMaxLength();

	    
}
